using System;
using System.Configuration;
using Framework.Library.Core.Utils.Miscellaneous;

namespace Framework.Library.Core.Utils.Configuration
{
    public abstract class ConfigurationElementCollectionBase<T> :
        ConfigurationElementCollection where T : ConfigurationElement, IIdentifiable
    {
        public override ConfigurationElementCollectionType CollectionType
        {
            get { return ConfigurationElementCollectionType.AddRemoveClearMap; }
        }

        public T this[int index]
        {
            get { return (T) BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                    BaseRemoveAt(index);

                BaseAdd(index, value);
            }
        }

        public new T this[string key]
        {
            get { return (T) BaseGet(key); }
        }

        public void Add(T element)
        {
            BaseAdd(element);
        }

        public void Clear()
        {
            BaseClear();
        }

        public bool Contains(string key)
        {
            return (BaseGet(key) != null);
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return Activator.CreateInstance<T>();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((T) element).Id;
        }

        public void Remove(T element)
        {
            Remove(element.Id);
        }

        public void Remove(string key)
        {
            BaseRemove(key);
        }

        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }
    }
}